import React, { PureComponent, Fragment, Component } from 'react';
import { connect } from 'dva';
import { Row, Col, Card, Form, Tabs, Table, Checkbox, Icon } from 'antd';
import moment from 'moment';
import { routerRedux } from 'dva/router';
import { imgPrex } from '../../utils/constData';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import VerticalTable from './VerticalTable';
import styles from './actDetail.less';

const FormItem = Form.Item;
const TabPane = Tabs.TabPane;
const dateFormat = 'YYYY-MM-DD';
const numToZh = ['一', '二', '三', '四', '五', '六', '日'];

@connect(({ activity }) => ({
	activity,
}))
@Form.create()
export default class EditActivity extends PureComponent {
	state = {
		record: {}, // 整个页面的基本信息
		fileList: [],
		file: null,
		image: null,
		endOpen: false,
		dateData: [],
		timeData: [],
		optData: [],
		currentDate: '',
		currentTime: '',
		cacheData: {},
		columns: [],
		datasource: [],
		multiArr: [],
		currentPage: 0,
	};
	componentDidMount() {
		this.props.dispatch({
			type: 'activity/fetchActDetail',
			payload: { actId: this.props.match.params.actId },
			callback: data => this._setBackData(data),
		});
	}
	_setBackData(data) {
		const dateData = this.calcDate(data);
		this.setState(
			{
				record: data,
				dateData,
			},
			() => {
				if(dateData.length>0){
					this.clickDate(dateData[0].date);
				}
			}
		);
	}
	_callback() {
		this.props.dispatch(routerRedux.goBack());
	}
	transformData = arr => {
		const obj = {};
		const tempArr = [];
		arr.forEach(item => {
			const key = `${item.startTime}-${item.endTime}`;
			if (obj[key]) {
				obj[key].push(item.appointDate);
			} else {
				obj[key] = [item.appointDate];
			}
			if (!tempArr.includes(item.appointDate)) {
				tempArr.push(item.appointDate);
			}
		});
		this.generateSources(obj);
		this.sliceArr(tempArr);
	};
	sliceArr = arr => {
		const tmp = arr.sort();
		const size = 7;
		const multiArr = [];
		for (let i = 0; i < tmp.length; i += size) {
			multiArr.push(tmp.slice(i, i + size));
		}
		this.setState(
			{
				multiArr,
			},
			() => {
				const { currentPage } = this.state;
				this.generateColumns(multiArr[currentPage], currentPage, multiArr.length - 1);
			}
		);
	};
	generateColumns = (arr, currentPage, num) => {
		const params = {
			currentPage,
			num,
		};
		const tempArr = arr.map((text, i) => ({
			title: this.renderBtn(text, i === 0 || i === arr.length - 1 ? i : undefined, params),
			dataIndex: text,
			align: 'center',
			render(t, record) {
				return <Checkbox checked={record.val.includes(text)} />;
			},
		}));
		const columns = [
			{
				title: '活动时间',
				dataIndex: 'key',
				align: 'center',
			},
			...tempArr,
		];
		this.setState({ columns });
	};
	generateSources = obj => {
		const keys = Object.keys(obj).sort();
		const datasource = keys.map(key => {
			return {
				key,
				val: obj[key],
			};
		});
		this.setState({
			datasource,
		});
	};
	renderBtn = (text, num, params) => {
		const weekDay = numToZh[moment(text).weekday()];
		if (num === 0) {
			return (
				<div>
					<Icon
						type="left"
						onClick={() => {
							this.clickLeft(params);
						}}
						className={styles['prev-week']}
					/>
					<span>{text}</span>
					<span>{`星期${weekDay}`}</span>
				</div>
			);
		} else if (num) {
			return (
				<div>
					<span>{text}</span>
					<span>{`星期${weekDay}`}</span>
					<Icon
						type="right"
						onClick={() => {
							this.clickRight(params);
						}}
						className={styles['next-week']}
					/>
				</div>
			);
		}
		return <div>{text}</div>;
	};
	clickLeft = ({ currentPage, num }) => {
		if (currentPage > 0) {
			currentPage--;
			this.setState(
				{
					currentPage,
				},
				() => {
					const { currentPage, multiArr } = this.state;
					this.generateColumns(multiArr[currentPage], currentPage, multiArr.length - 1);
				}
			);
		}
	};
	clickRight = ({ currentPage, num }) => {
		if (currentPage < num) {
			currentPage++;
			this.setState(
				{
					currentPage,
				},
				() => {
					const { currentPage, multiArr } = this.state;
					this.generateColumns(multiArr[currentPage], currentPage, multiArr.length - 1);
				}
			);
		}
	};
	changeState = (name, value) => {
		this.setState({
			[name]: value,
		});
	};
	calcDate = ({ actDates }) => {
		const arr = actDates
			.filter(i => i)
			.map(({ appointDate }) => appointDate)
			.sort();
		return arr.map(d => {
			return {
				date: moment(d).format(dateFormat),
				weekday: `周${numToZh[moment(d).weekday()]}`,
			};
		});
	};
	// 点击日期获得时间段
	clickDate = opts => {
		console.log(opts)
		const {
			record: { actId },
		} = this.state;
		const date = typeof opts === 'string' ? opts : opts.date;
		this.props.dispatch({
			type: 'activity/getActDateTimes',
			payload: {
				actId,
				appointDate: date,
			},
			callback: data => {
				this.changeState('timeData', data);
				this.clickTime(data[0]);
			},
		});
		this.changeState('currentDate', date);
	};
	// 点击时间获得历史记录信息
	clickTime = opts => {
		if (!opts || !opts.startTime || !opts.endTime) {
			return;
		}
		const { record } = this.state;
		this.changeState('currentTime', `${opts.startTime}-${opts.endTime}`);
		const params = {
			actId: record.actId,
			appointDate: opts.appointDate,
			startTime: opts.startTime,
			endTime: opts.endTime,
		};
		this.props.dispatch({
			type: 'activity/getUserActTimeHistory',
			payload: params,
			callback: data => {
				this.changeState('optData', data);
			},
		});
	};
	clickTab = activeKey => {
		if (activeKey === '2') {
			this.transformData(this.state.record.timeTables);
		}
	};

	//点击核销与取消核销
	writeOff = (opts)=>{
		const thisCurrentdate=this.state.currentDate
		const timearray=this.state.currentTime.split("-")
		const currentStartTime= timearray[0]
		const currentEndTime= timearray[1]
		if (!opts) {
			return;
		}
		const { record } = this.state;
		const params = {
			hisId: opts.hisId,
			appointDate: thisCurrentdate,
			startTime: currentStartTime,
			endTime: currentEndTime,
			isWriteOff:opts.isWriteOff ? 0:1,
		};
		this.props.dispatch({
			type: 'activity/actWriteOff',
			payload: params,
			callback: () => {
				this.props.dispatch({
					type: 'activity/fetchActDetail',
					payload: { actId: record.actId },
					callback: data => this._setBackData(data),
				});
			},
		});
	}

	render() {
		const { activity } = this.props;
		const { currentDate, currentTime, record, dateData, timeData, optData } = this.state;
		const recordinfo = (
			<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
				<Col md={4} sm={24}>
					<div className={styles.actimg}>
						<img src={imgPrex + record.actImg} />
					</div>
				</Col>
				<Col md={20} sm={24}>
					<Card>
						<div className={styles.topDiv}>
							<div>课程名称：{record.actName}</div>
							<div>上课门店：{record.storeName}</div>
							<div>适用人群：{record.actApply == 0 ? '普通会员':(record.actApply == 1?'借阅会员':'vip会员')}</div>
						</div>
						<div className={styles.topDiv}>
							<div>最大活动次数：{record.actAttendCount}</div>
							<div>每场人数：{record.actUserCount}</div>
							<div>
								有效时间：{record.startTime}至{record.endTime}
							</div>
						</div>
						<div className={styles.botDivss}>
							<div>活动时间：{record.actTimes}</div>
						</div>
					</Card>
				</Col>
			</Row>
		);
		const { columns, datasource } = this.state;
		const tableConfig = {
			bordered: true,
			pagination: false,
		};
		return (
			<PageHeaderLayout title="活动详情">
				{recordinfo}
				<Tabs defaultActiveKey="1" onChange={this.clickTab}>
					<TabPane tab="预约记录" key="1">
						<VerticalTable
							dateData={dateData}
							timeData={timeData}
							optData={optData}
							currentDate={moment(currentDate).format(dateFormat)}
							currentTime={currentTime}
							clickDate={this.clickDate}
							clickTime={this.clickTime}
							writeOff={this.writeOff}
						/>
					</TabPane>
					<TabPane tab="课程排表" key="2">
						<Table {...tableConfig} columns={columns} dataSource={datasource} />
					</TabPane>
				</Tabs>
			</PageHeaderLayout>
		);
	}
}
